from datetime import datetime

from common import get_logger, insert_data
from database import Video, Audio, Content, Record, get_db_session, Image
from douyin_utils import crawl_douyin_videos, extract_audio
from cos_utils import upload_to_cos
from asr_utils import audio_to_text
from plat_utils import douyin_to_plat_text
from image_utils import generate_images_by_text
from xhs_publish import post_to_xhs
from image_utils import remove_images_watermark
from common import remove_dir_content
from zhihu_publish import post_to_zhihu
from bjh_publish import post_to_bjh

logger = get_logger(__name__)


def main():
    logger.info("流程开始")
    try:
        # 1.爬取热门视频
        video_files = crawl_douyin_videos("脆桃")
        for video_item in video_files:
            video_path = video_item.get("file_path")
            title = video_item.get("title")
            logger.info(f"开始处理视频文件:{video_path}")
            # 将视频信息存入视频表
            video_data = insert_data(
                Video,
                {
                    "video_path": video_path,
                    "title": title,
                    "create_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                },
            )
            # 2.把视频转成音频
            mp3_path = extract_audio(video_path)
            logger.info(f"音频地址:{mp3_path}")
            # 3.上传音频到腾讯云COS
            cos_url = upload_to_cos(mp3_path)
            logger.info(f"上传音频到腾讯COS成功:{cos_url}")
            # 将音频信息存入音频表
            audio_data = insert_data(
                Audio,
                {
                    "video_id": video_data["id"],
                    "audio_path": mp3_path,
                    "cos_url": cos_url,
                    "create_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                },
            )
            # 4.把音频转成文字
            douyin_text = audio_to_text(cos_url)
            logger.info(f"音频转文字成功:{douyin_text}")

            # 5.把抖音的文案改为指定平台的爆款文案
            plat_title, plat_intro, plat_tags = douyin_to_plat_text(douyin_text)
            logger.info(
                f"转小红书文案:plat_title:{plat_title} plat_intro:{plat_intro} plat_tags:{plat_tags}"
            )
            # 将内容信息存入内容表
            content_data = insert_data(
                Content,
                {
                    "audio_id": audio_data["id"],
                    "raw_text": douyin_text,
                    "platform": "小红书",
                    "title": plat_title,
                    "intro": plat_intro,
                    "tags": ",".join(plat_tags),
                    "create_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                },
            )
            # 6.根据文案生成图片
            image_datas = generate_images_by_text(plat_title, plat_intro)
            logger.info(f"图片生成成功:{image_datas['img_paths']}")
            # 7.去除图片中的水印
            img_paths = remove_images_watermark(image_datas["filenames"])
            logger.info(f"图片去水印完成:{img_paths}")
            # 将图片内容存入图片表
            insert_data(
                Image,
                {
                    "text_id": content_data["id"],
                    "image_path": ",".join(img_paths),
                    "create_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                },
            )
            # 8.清空水印图片文件夹
            remove_dir_content("pre_images")
            # 9.1发到内容到小红书里
            post_item = post_to_xhs(
                title=plat_title, intro=plat_intro, tags=plat_tags, img_paths=img_paths
            )
            # 9.2 发布内容到知乎
            post_item = post_to_zhihu(
                title=plat_title, intro=plat_intro, img_paths=img_paths
            )
            # 9.3 发布内容到百家号
            post_item = post_to_bjh(
                title=plat_title, intro=plat_intro, img_paths=img_paths
            )

            # 将发布记录存入记录表
            insert_data(
                Record,
                {
                    "text_id": content_data["id"],
                    "platform": "小红书",
                    "status": post_item.get("status"),
                    "publish_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    "extra_info": post_item.get("extra_info"),
                },
            )
            # 10.发布内容到知乎尽量再找一个平台 比如头条号 百家号

    except Exception as e:
        logger.error(f"主流程执行出错:{e}")


if __name__ == "__main__":
    main()
